import { Button, LoadIndicator, Popup, SelectBox, TextBox } from "devextreme-react";
import { useModel } from "umi";
import { DevToolBar, CpasIcon, DevGrid } from '~/public/cpas-ui';
import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react"
import { Item } from 'devextreme-react/toolbar';
import { adjustingEntryInit, getTopKMMCList, getDataList, updateKMMap, updateSelectState, updateSelectStateAdjustingEntry, AdjustingEntrySave } from "./service"
import { intl, moneyFormatCol, nanoid10, pushNumberData } from "@/utils";
import { filter, throttle } from "lodash";
// import DataGrid from "devextreme-react/data-grid";
// import { Column } from "devextreme-react/data-grid";
// import "./index.less"
import CarryEntryPopup from "~/public/cpas-business/components-bs/CarryEntryPopup";
import SetClassiFication from "../SetClassiFication"
// import { getOneBillDetail } from "../../../../service";
import notify from "devextreme/ui/notify";
// import { gridData } from "./testGridData";

const ClassiFication: React.FC<any> = React.forwardRef((props: any, ref) => {
    const { BillID, isQC } = props;
    const { setIsShowGlobalLoad } = useModel('useAdjustModel');


    const { initialState } = useModel('@@initialState');
    const { dbname } = initialState?.curPart as API.CurPart;
    const { username } = initialState?.curUser as API.CurUser;

    const Divstyle: React.CSSProperties = { display: 'flex', alignItems: "center", justifyContent: "center", marginRight: '10px' };

    const diaParams = useRef<any>();
    const devGridRef = useRef<any>();
    const carryEntryRef = useRef<any>();
    const SetClassiFicationRef = useRef<any>();
    const resultNumber = useRef<any>(0);

    const [visiblePopup111, setVisiblePopup111] = useState<boolean>(false);
    const [visiblePopupKey, setVisiblePopupKey] = useState<string>('');

    const [visiblePopup, setVisiblePopup] = useState<boolean>(false);
    // const [typeText, setTypeText] = useState<string>('全部');
    const [typeTextID, setTypeTextID] = useState<number>(6);

    const [totalfilter, setTotalfilter] = useState<any[]>([]);
    const [subjectText, setSubjectText] = useState<string>('全部');
    const [subjectListData, setSubjectListData] = useState<any[]>([]);
    const subjectSelectionDataRef = useRef<any>([]);
    const [seachText, setSeachText] = useState<string>('');
    // 合计数 函数
    function addValues(array: any[], property: string) {
        return array.reduce((sum, current) => sum + current[property], 0);
    }

    function selectCertainRowsWithGUIDValues(r: any, isBoolean: boolean = true) {
        setVisiblePopup111(true);
        if (Array.isArray(r)) {
            const result = addValues(r, 'QCSDS') + addValues(r, 'SDS');
            const bbb = pushNumberData(`${result}`);
            resultNumber.current = bbb.formattedPrice;
            subjectSelectionDataRef.current = r;
            if (isBoolean) {
                devGridRef.current?.instance.selectAll();
            } else {
                const selectGuids: any[] = r.map((item: any) => {
                    if (item.CFLNo && item.CFLName) {
                        return item.GUID;
                    }
                }).filter((item: any) => {
                    if (item) {
                        return { GUID: item }
                    }
                    return;
                });
                devGridRef.current?.instance.selectRows(selectGuids);
            }
            setVisiblePopup111(false);

        }

    };

    const fetchDataisRefresh = async (tempKMMC1: string, tempZWType6: any) => {
        if (!diaParams.current?.Data_ID) return;
        subjectSelectionDataRef.current = [];
        setVisiblePopupKey(nanoid10());
        setVisiblePopup111(true);
        const res = await getDataList({
            dbname,
            billID: BillID,
            Data_ID: diaParams.current?.Data_ID,
            KMMC: tempKMMC1 !== "全部" ? tempKMMC1 : "",
            ZWType: tempZWType6 !== 6 ? tempZWType6 : '',
            isRefresh: false
        });
        if (res.success) {
            const devGridInstance = devGridRef.current?.instance;
            if (devGridInstance) {
                setTotalfilter(res.data);
                setTimeout(() => {
                    selectCertainRowsWithGUIDValues(res.data);
                }, 300);

            }


        }
    };

    const fetchDataInit = async () => {
        const res = await adjustingEntryInit({
            dbname,
            billID: BillID,
            isQC: isQC,
            Data_ID: diaParams.current.Data_ID
        });
        if (res.success) {

            setVisiblePopup111(true);
            const r = await getTopKMMCList({
                dbname,
                billID: BillID,
                Data_ID: diaParams.current?.Data_ID
            });
            if (r.success) {
                setSubjectText('全部');
                setTypeTextID(6);
                r.data.unshift({ KMMC: "全部" })
                setSubjectListData(r.data);
                await fetchDataisRefresh('', '');
            } else {
                setSubjectListData([]);
            };
            setIsShowGlobalLoad(false);
        } else {
            notify(`初始化重分类科目失败！`, "error", 3000);
            setIsShowGlobalLoad(false);
        }
    };



    const columns123: any = [
        {
            allowEditing: false,
            dataField: 'YSKMBH',
            caption: '科目编号',
            dataType: "string",
            width: 120,
            alignment: 'left'
        },
        {
            allowEditing: false,
            dataField: 'KMMC',
            caption: '科目名称',
            dataType: "string",
            alignment: 'left'
        }, {
            allowEditing: false,
            dataField: 'HSXMLXMC',
            caption: '核算项目类型',
            dataType: "string",
            alignment: 'left'
        }, {
            allowEditing: false,
            dataField: 'HSXMMC',
            caption: '辅助账名称',
            dataType: "string",
            alignment: 'left'
        }, {
            allowEditing: false,
            dataField: 'CFLNo',
            caption: '对方科目编号',
            dataType: "string",
            width: 110,
            alignment: 'left'
        }, {
            allowEditing: false,
            dataField: 'CFLName',
            caption: '对方科目名称',
            dataType: "string",
            width: 160,
            alignment: 'left'
        },
        {
            allowEditing: false,
            dataField: 'QCSDS',
            caption: '期初审定数',
            dataType: "string",
            width: 100,
            alignment: 'left',
            cellRender: (cell: any) => {
                return cell.data.QCSDS === 0 ? "" : moneyFormatCol(cell.data.QCSDS);
            }
        },
        {
            allowEditing: false,
            dataField: 'SDS',
            caption: '期末审定数',
            dataType: "string",
            width: 100,
            alignment: 'left',
            cellRender:
                (cell: any) => {
                    return cell.data.SDS === 0 ? "" : moneyFormatCol(cell.data.SDS);
                }
        }
    ];


    // 科目下拉事件 过滤
    const SubjectSelectionClick = useCallback((e: any) => {
        setSubjectText(e.selectedItem.KMMC);
        fetchDataisRefresh(e.selectedItem.KMMC, typeTextID);
    }, [typeTextID, BillID]);
    // 财务类型 过滤
    const SubjectSelectionTypeClick = useCallback((e: any) => {
        // setTypeText(e.selectedItem.name);
        setTypeTextID(e.selectedItem.id);
        fetchDataisRefresh(subjectText, e.selectedItem.id);
    }, [subjectText, BillID]);

    useImperativeHandle(ref, () => ({
        show: (params: any) => {
            setVisiblePopup(true);
            diaParams.current = params;
            setVisiblePopup111(true);
            setSeachText('');
            // 初始化需重分类的数据
            fetchDataInit();
        },
    }));

    // 模糊搜索
    const inputSearch = (content: any) => {
        devGridRef.current.instance.searchByText(content || "");
    };
    const throttleSearch = throttle(inputSearch, 100);
    const getInputValue = (e: any) => {
        const { event } = e;
        setSeachText(event.target.value);
        throttleSearch(event.target.value)
    };

    //更新全选和单选选中状态
    const onSelectionChangeds = async (e: any) => {
        // setStartupSelectedKeys(e.selectedRowKeys);
        if (e.currentSelectedRowKeys.length === 1) {
            await updateSelectStateAdjustingEntry({
                dbname,
                billID: BillID,
                isSelected: true,
                GUIDs: e.currentSelectedRowKeys[0],
            });
            return;
        }
        if (e.currentDeselectedRowKeys.length === 1) {
            await updateSelectStateAdjustingEntry({
                dbname,
                billID: BillID,
                isSelected: false,
                GUIDs: e.currentDeselectedRowKeys[0],
            });
            return;
        }
        //全选状态
        const isSelectAll = totalfilter.length === e.selectedRowKeys.length;
        //非全选
        const isDeSelectAll = totalfilter.length === e.currentDeselectedRowKeys.length;
        if (isSelectAll) {
            await updateSelectState({
                dbname,
                billID: BillID,
                KMMC: subjectText === "全部" ? '' : subjectText,
                ZWType: typeTextID === 6 ? '' : typeTextID,
                isSelected: true
            });
            return;
        }
        if (isDeSelectAll) {
            console.log("触发----");
            await updateSelectState({
                dbname,
                billID: BillID,
                KMMC: subjectText === "全部" ? '' : subjectText,
                ZWType: typeTextID === 6 ? '' : typeTextID,
                isSelected: false
            });
            return;
        }
    };
    // 双击 事件
    const selectCellDblClick = async (res: any) => {
        if (res.rowType !== "header" && res.rowIndex !== -1) {
            carryEntryRef.current.show({
                dbname,
                Data_ID: diaParams.current?.Data_ID,
                // 是否辅助账
                isHasFZZ: res.data.ZWType === 0 ? false : true,
                editUser: username,
                selectMode: "0",
                // 选择 模式 0：单选 1：多选连机选择
                auxiliaryState: true,
                // 是否为辅助帐
                // 是否可以选择上级科目
                isSelectSuperior: false,
                okCallback: async (r: any) => {
                    // // debugger;
                    const resRow = r?.row ? r.row.data : r;
                    if (!resRow) return;
                    const KMBH = resRow.HSXMLXBH ? resRow.YSKMBH + ';' + resRow.HSXMLXBH + ';' + resRow.YSHSXMBH : resRow.YSKMBH;
                    devGridRef.current.instance.cellValue(res.rowIndex, 'CFLNo', KMBH);
                    // KMMC + ';' + HSXMLXMC + ';' + YSHSXMMC
                    const KMMC = resRow.HSXMLXMC ? resRow.KMMC + ';' + resRow.HSXMLXMC + ';' + resRow.YSHSXMMC : resRow.KMMC
                    devGridRef.current.instance.cellValue(res.rowIndex, 'CFLName', KMMC);
                    devGridRef.current.instance.saveEditData();
                    await updateKMMap({
                        dbname,
                        billID: BillID,
                        YSKMBH: `${resRow.YSKMBH}`,
                        GUID: res.data.GUID,
                        YSHSXMBH: resRow.YSHSXMBH,
                        HSXMLXMC: resRow.HSXMLXMC,
                        HSXMLXBH: resRow.HSXMLXBH,
                        KMMC: resRow.KMMC,
                        KMBH: resRow.KMBH,
                        HSXMMC: resRow.HSXMMC,
                        HSXMBH: resRow.HSXMBH,
                        YSHSXMMC: resRow.YSHSXMMC,
                        itemNames3: resRow.itemNames3,
                        YSKMMC: resRow.YSKMMC,
                    });
                },
            });
        }
    }


    // 批量设置对方科目
    const BatchAccount = () => {
        // setClassiVisible(true);
        setVisiblePopup111(true);
        SetClassiFicationRef.current.show({
            DataId: diaParams.current?.Data_ID,
            BillID: BillID,
            okClick: async () => {
                setVisiblePopup111(true);
                const r = await getDataList({
                    dbname,
                    billID: BillID,
                    Data_ID: diaParams.current?.Data_ID,
                    KMMC: subjectText !== "全部" ? subjectText : "",
                    ZWType: typeTextID !== 6 ? typeTextID : '',
                    isRefresh: true
                });
                if (r.success) {
                    setTotalfilter(r.data);
                    setTimeout(() => {
                        selectCertainRowsWithGUIDValues(r.data, false);
                    }, 300);
                } else {
                    // setClassiVisible(false);
                    setVisiblePopup111(false);
                }
            },
            cancelClick: () => {
                setVisiblePopup111(false);
            }
        })
    };

    // 点击关闭按钮逻辑
    const onHiding = () => {
        setSubjectListData([]);
        setTotalfilter([]);
        setSubjectText("全部");
        // setTypeTextID(6);
        setTypeTextID(6);
        resultNumber.current = 0;
        devGridRef.current?.instance.clearFilter();
        setSeachText('');
        setVisiblePopup(false);
        if (diaParams.current?.cancelCallback) {
            diaParams.current?.cancelCallback();
        }
        setVisiblePopup111(false);
        setIsShowGlobalLoad(false);
    };

    const FilterMethod = async () => {
        const res = await AdjustingEntrySave({
            dbname,
            billID: BillID,
            Data_ID: diaParams.current?.Data_ID,
            isQC: isQC
        });
        if (res) {
            onHiding();
            diaParams.current?.okCallback();
        } else {
            setIsShowGlobalLoad(false);
            setVisiblePopup111(false);
            notify(`保存失败，重分类`, "error", 3000);
        }
    }

    const getSelectedRowsData = (totalData: any[], selData: string[]) => {
        // 将 totalData 转换为 Map 以便高效查找
        const totalMap = new Map(totalData.map(item => [item.GUID, item]));

        // 从 totalMap 中查找 selData 中的 GUID 对应的数据
        const selectedRowsData = selData.map(guid => totalMap.get(guid)).filter(Boolean);

        return selectedRowsData;
    };

    const Ok_Fun = () => {

        const devGridInstance = devGridRef.current?.instance;
        if (devGridInstance) {
            setIsShowGlobalLoad(true);
            setVisiblePopup111(true);
            let selectedRowsDataArr = devGridInstance.getSelectedRowKeys();
            let selectedRowsData = getSelectedRowsData(totalfilter, selectedRowsDataArr);
            const filteredIndexes = selectedRowsData.filter((item: any) => {
                if (!item.CFLKMBH && !item.CFLName) {
                    return item;
                }
            });
            if (filteredIndexes.length === 0) {
                FilterMethod();
            } else {
                setVisiblePopup111(false);
                setIsShowGlobalLoad(false);
                notify(`有[${filteredIndexes.length}]条记录，未设置重分类科目!`, "warning", 3000);
            }
        }
    }

    return (
        <div >
            <Popup
                shadingColor='rgba(0, 0, 0, 0)'
                shading={true}
                visible={visiblePopup}
                title='负值重分类'
                {...props}
                width={'85vw'}
                // height={'50vh'}
                minWidth={500}
                minHeight={300}
                animation={{ duration: 1 }}
                onHiding={onHiding}
                // onShown={() => {
                //     // 初始化需重分类的数据
                //     fetchDataInit();
                // }}
                // onResizeEnd={(e) => {
                //     setSize({ width: e.width, height: e.height });
                //     devGridRef.current?.instance.dispose();
                // }}
                toolbarItems={[
                    {
                        toolbar: 'bottom',
                        location: 'before',
                        cssClass: 'bottomTextStyle',
                        text: "注: 由于企业科目自身特性，重分类科目可能匹配不完全准确，请检查后自行设置"
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.cancel', '取消'),
                            onClick: () => onHiding()

                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.ok', '确定'),
                            type: 'default',
                            onClick: () => {
                                Ok_Fun();
                            }
                        },
                    },
                ]}
            >
                <div style={{ position: "relative", width: '100%', height: '100%', overflow: 'visible' }}>
                    {visiblePopup111 && <div style={{
                        position: 'absolute', width: '100%', height: '100%', display: 'flex', alignItems: "center", justifyContent: "center",
                        opacity: 0.5, zIndex: "99999", background: "#ddd"
                    }}>
                        <LoadIndicator id="medium-indicator" height={50} width={50} />
                    </div>}

                    <div style={{ width: '100%', marginBottom: '8px', height: '80px', }}>
                        <DevToolBar.Default >
                            <Item location="before">
                                <div style={{ display: 'flex', alignItems: "center", }}>
                                    <div style={Divstyle}>
                                        <span style={{ marginRight: '8px' }}> {intl('report.subject.account', '账套:')} </span>
                                        <TextBox
                                            width={130}
                                            value={diaParams.current?.EntryName}
                                            valueChangeEvent='keyup'
                                            readOnly={true}
                                            showClearButton={true}
                                        />
                                    </div>
                                    <div style={Divstyle}>
                                        <span style={{ marginRight: '8px' }}>调整期间:</span>
                                        <TextBox
                                            width={80}
                                            valueChangeEvent='keyup'
                                            readOnly={true}
                                            showClearButton={true}
                                            value={isQC ? "期初" : "期末"}
                                        />
                                    </div>
                                    <div style={Divstyle}>
                                        <span style={{ marginRight: '8px' }}>科目:</span>
                                        <SelectBox
                                            width={130}
                                            dataSource={subjectListData}
                                            displayExpr='KMMC'
                                            valueExpr='KMMC'
                                            // defaultValue="全部"
                                            value={subjectText}
                                            onSelectionChanged={SubjectSelectionClick}
                                        />
                                    </div>
                                    <div style={Divstyle}>
                                        <span style={{ marginRight: '8px' }}>账务类型:</span>
                                        <SelectBox
                                            width={100}
                                            dataSource={[
                                                {
                                                    id: 6,
                                                    name: "全部"
                                                },
                                                {
                                                    id: 0,
                                                    name: "总账"
                                                },
                                                {
                                                    id: 1,
                                                    name: "辅助账"
                                                }
                                            ]}
                                            displayExpr='name'
                                            valueExpr='id'
                                            // defaultValue="全部"
                                            value={typeTextID}
                                            onSelectionChanged={SubjectSelectionTypeClick}
                                        />
                                    </div>
                                </div>
                            </Item>
                            <Item location="after">
                                <div style={{ display: 'flex', alignItems: "center", justifyContent: "center", marginRight: '40px' }}>
                                    <Button text="批量设置对方科目" onClick={BatchAccount} />
                                </div>
                            </Item>
                        </DevToolBar.Default>

                        <div style={{ marginTop: '10px' }}>
                            <DevToolBar.Default>
                                <Item location="before" text='提示：双击可重新选择对方科目' cssClass='TitleTextStyle' />
                                <Item location="before" text={`合计数: ${resultNumber.current}`} cssClass='TitleTextStyle' />
                                <Item location="after">
                                    <div style={Divstyle}>
                                        <TextBox onInput={(e: any) => getInputValue(e)}
                                            className="TextBoxButtons_Style"
                                            style={{ marginRight: '8px' }}
                                            value={seachText}
                                            buttons={[
                                                {
                                                    location: "before",
                                                    name: "search",
                                                    options: {
                                                        icon: "iconfont icon-search",
                                                        disabled: true,
                                                    },
                                                },
                                            ]}
                                        />

                                        <div className="IconRefresh_Style" style={{ width: '36px' }} >
                                            <CpasIcon
                                                type="icon-refresh"
                                                fontSize={16}
                                                onClick={() => {
                                                    fetchDataisRefresh(subjectText, typeTextID);
                                                }}
                                            />
                                        </div>
                                    </div>
                                </Item>
                            </DevToolBar.Default>
                        </div>
                    </div>
                    {useMemo(() => {
                        return <DevGrid.Default
                            className='PaperDevSortableGrid devHeadersCenter'
                            ref={devGridRef}
                            key={visiblePopupKey}
                            dataSource={totalfilter}
                            columns={columns123}
                            showBorders={true}
                            showColumnHeaders={true}
                            hoverStateEnabled={true}
                            showRowLines={true}
                            allowColumnResizing={true}
                            columnResizingMode="widget"
                            keyExpr="GUID"
                            // allowEditing={false}
                            // onContentReady={(e) => {
                            //     const scrollable = devGridRef.current?.instance?.getScrollable();
                            //     if (isScrollTop && scrollable) {
                            //         scrollable.scrollTo({ top: 0 });
                            //         setIsScrollTop(false);
                            //     }
                            // }}
                            height={500}
                            scrolling={{
                                mode: "virtual",
                                rowRenderingMode: "virtual",
                                renderAsync: true
                            }}
                            headerFilter={{ visible: false }}
                            filterPanel={{ visible: false }}
                            filterRow={{ visible: false }}
                            paging={{
                                enabled: false
                            }}
                            // selectedRowKeys={startupSelectedKeys}
                            selection={{
                                mode: 'multiple',
                                // selectAllMode: 'allPages', //允许选中当前界面的所有数据
                                // showCheckBoxesMode: 'always'
                            }}
                            onCellDblClick={selectCellDblClick}
                            onSelectionChanged={onSelectionChangeds}
                            loadPanel={{
                                enabled: true,
                                text: 'Loading...',
                            }}
                        />
                    }, [totalfilter, visiblePopupKey])}


                </div>
            </Popup >
            <CarryEntryPopup ref={carryEntryRef} />
            <SetClassiFication ref={SetClassiFicationRef} isQC={isQC} width={1250} height={730} />
        </div >
    )
});

export default React.memo(ClassiFication); 